package com.laikan.reader.database;

import android.content.Context;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.utils.MD5;
import org.greenrobot.greendao.database.Database;
import thirdparty.greendao.database.DaoMaster;
import thirdparty.greendao.database.DaoSession;

/**
 * Created by anrun on 8/10/16.
 */
public class DBManager {

    private Context context;
    private DBOpenHelper dbOpenHelper;
    private static DBManager instance;
    private static final String DB_NAME = "laikan.db";
    private static final String DB_ENCRYPTED_NAME = "laikan_encrypted.db";
    public static final boolean ENCRYPTED = true;

    private DaoSession daoSession;

    private DBManager(Context context) {
        this.context = context;
        dbOpenHelper = new DBOpenHelper(context, ENCRYPTED ? DB_ENCRYPTED_NAME : DB_NAME, null);
        daoSession = new DaoMaster(getReadableDatabase()).newSession();
    }

    public static DBManager getInstance() {
        if (instance == null) {
            synchronized (DBManager.class) {
                if (instance == null) {
                    instance = new DBManager(LaikanApplication.applicationContext);
                }
            }
        }
        return instance;
    }

    public Database getReadableDatabase() {
        if (dbOpenHelper == null) {
            dbOpenHelper = new DBOpenHelper(context, ENCRYPTED ? DB_ENCRYPTED_NAME : DB_NAME, null);
        }
        Database db = ENCRYPTED ? dbOpenHelper.getEncryptedWritableDb(getEncryptKey()) : dbOpenHelper.getWritableDb();
        return db;
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    private String getEncryptKey() {
        String key = MD5.getMD5Str("Lai" + DeviceUtil.getImei(context) + "Kan");
        key = MD5.getMD5Str("laikan" + key).substring(8, 23);
        return key;
    }
}
